package com.polaris.live.im.db.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.polaris.live.App
import com.polaris.live.im.db.dao.GreetMessageEntityDao
import com.polaris.live.im.db.dao.MessageEntityDao
import com.polaris.live.im.db.dao.MessageExcludeEntityDao
import com.polaris.live.im.db.dao.PurchaseOrderEntityDao
import com.polaris.live.im.db.dao.PurchasePretreatmentEntityDao
import com.polaris.live.im.db.dao.SessionListEntityDao
import com.polaris.live.im.db.entity.GreetMessageEntity
import com.polaris.live.im.db.entity.MessageEntity
import com.polaris.live.im.db.entity.MessageExcludeEntity
import com.polaris.live.im.db.entity.PurchaseOrderEntity
import com.polaris.live.im.db.entity.PurchasePretreatmentEntity
import com.polaris.live.im.db.entity.SessionEntity


/**
 * im的Database
 *
 * @author Created by lucas on 2024/1/1 07:50
 * @since 1.0.0
 */
@Database(
    entities = [
        MessageEntity::class,
        SessionEntity::class,
        MessageExcludeEntity::class,
        PurchasePretreatmentEntity::class,
        PurchaseOrderEntity::class,
        GreetMessageEntity::class
    ],
    version = 2,
    exportSchema = true
)
abstract class AppDatabase : RoomDatabase() {

    abstract fun messageDao(): MessageEntityDao

    abstract fun sessionListDao(): SessionListEntityDao

    abstract fun messageExcludeDao(): MessageExcludeEntityDao

    abstract fun purchasePretreatmentEntityDao(): PurchasePretreatmentEntityDao

    abstract fun purchaseOrderEntityDao(): PurchaseOrderEntityDao

    abstract fun greetMessageEntityDao(): GreetMessageEntityDao

    companion object {

        private const val NAME_DATABASE = "chat"

        val instance: AppDatabase by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            buildDatabase(App.instance)
        }

        private fun buildDatabase(context: Context): AppDatabase {
            return Room.databaseBuilder(context, AppDatabase::class.java, NAME_DATABASE)
                .addMigrations(MIGRATION_1_2)
                .build()
        }

        private var MIGRATION_1_2: Migration = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "create table greet_message (" +
                            "table_id TEXT NOT NULL PRIMARY KEY," +
                            "user_id INTEGER NOT NULL," +
                            "other_id INTEGER NOT NULL," +
                            "push_detail_id INTEGER" +
                            ")"
                )
                database.execSQL(" CREATE UNIQUE INDEX index_greet_message_user_id_other_id ON greet_message (user_id,other_id) ")

            }
        }
    }
}